package com.woniuxy.sale.service.impl;

import com.woniuxy.commons.entity.sale.PackingMsg;
import com.woniuxy.commons.entity.sale.dto.ChooseProduceMsgDto;
import com.woniuxy.commons.result.Result;
import com.woniuxy.sale.mapper.PackingMsgDao;
import com.woniuxy.sale.mapper.ProductDao;
import com.woniuxy.sale.service.PackingMsgService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: CHL  <br/>
 * @ToDo: <br>
 * Date: 2022/4/21:10:58  <br/>
 * Description:
 */
@Service
public class PackingMsgServiceImpl implements PackingMsgService {
    @Resource
    PackingMsgDao packingMsgDao;

    @Resource
    ProductDao productDao;
    @Override
    public int insert(PackingMsg packingMsg) {
        int insert = packingMsgDao.insert(packingMsg);
        int id = packingMsg.getId();
        List<Integer> packingIds = packingMsg.getPackingId();
        //同步更改那些被打包的产品
        productDao.updatePackingProduct(id,packingIds);
        return insert;
    }

    @Override
    public List<PackingMsg> selectPackingMsgByPackingNum(String packingNum) {
        return productDao.selectPackingMsgByPackingNum(packingNum);
    }

    @Override
    public List<ChooseProduceMsgDto> selectProductByProductId(int id) {
        return productDao.selectProductByProductId(id);
    }

    private final ConcurrentHashMap<String, Long> savePsIdes = new ConcurrentHashMap();


    @Override
    @Transactional
    public Result updatePackingStatus(Integer psId) {
        String key = String.valueOf(psId).intern();
        //TODO 判断两次返回的值是否是同一个 如果是 说明之前还没有设置过值 可以直接进行操作
        // 否则 需要等待
        Long time = System.currentTimeMillis();

        while (true) {
            // 存入到map 如果第一次存入 返回的是本身存入的value
            if (time.equals(savePsIdes.computeIfAbsent(key, value -> time))) {


                packingMsgDao.updatePackingStatus(psId);

                savePsIdes.remove(key);

                break;

            }
        }
        return Result.ok();

    }
}
